package com.geekai.chat.service.impl;

import org.springframework.stereotype.Service;

import com.geekai.chat.config.AdminProperties;
import com.geekai.chat.config.JwtUtil;
import com.geekai.chat.dto.LoginRequest;
import com.geekai.chat.dto.LoginResponse;
import com.geekai.chat.service.AdminService;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class AdminServiceImpl implements AdminService {

	private final AdminProperties adminProperties;
	private final JwtUtil jwtUtil;

	@Override
	public LoginResponse login(LoginRequest loginRequest) {
		String configuredUsername = adminProperties.getUsername();
		String configuredPassword = adminProperties.getPassword();

		if (configuredUsername == null || configuredPassword == null) {
			throw new RuntimeException("管理员未配置");
		}

		if (!configuredUsername.equals(loginRequest.getUsername()) ||
				!configuredPassword.equals(loginRequest.getPassword())) {
			throw new RuntimeException("用户名或密码错误");
		}

		String token = jwtUtil.generateToken(configuredUsername, "admin");

		LoginResponse response = new LoginResponse();
		response.setToken(token);
		response.setUsername(configuredUsername);
		response.setNickname(adminProperties.getName());
		response.setEmail(adminProperties.getEmail());
		response.setAvatar(adminProperties.getAvatar());
		return response;
	}
}